package world.criver.imagecompresstool.function;

import com.sun.jna.Pointer;
import com.sun.jna.platform.win32.Kernel32;
import com.sun.jna.platform.win32.User32;
import com.sun.jna.platform.win32.WinDef;
import com.sun.jna.platform.win32.WinUser;
import javafx.application.Platform;
import javafx.stage.Stage;
import world.criver.imagecompresstool.application.appColorPicker;
import world.criver.imagecompresstool.data.daConfig;
import world.criver.imagecompresstool.enums.enumKeyCode;

public class funHotKey {
    private WinUser.HHOOK hook;
    private String hotkeys="";
    /**
     * 按键触发回调函数
     */
    private WinUser.LowLevelKeyboardProc keyboardProc=new WinUser.LowLevelKeyboardProc(){
        @Override
        public WinDef.LRESULT callback(int i, WinDef.WPARAM wparam, WinUser.KBDLLHOOKSTRUCT kb) {
            if(wparam.intValue()==WinUser.WM_KEYDOWN){
                for(enumKeyCode k: enumKeyCode.values()){
                    if(kb.vkCode==k.getId()){
                        listenKey(k.name().replaceAll("_",""));
                    }else if(kb.vkCode==163){
                        listenKey("Ctrl");
                        break;
                    }else if(kb.vkCode==160){
                        listenKey("Shift");
                        break;
                    }else if(kb.vkCode==165){
                        listenKey("Alt");
                        break;
                    }
                }
            }
            return User32.INSTANCE.CallNextHookEx(hook,i,wparam,new WinDef.LPARAM(Pointer.nativeValue(kb.getPointer())));
        }
    };

    /**
     * 添加钩子
     */
    public void addHook(){
        //模块句柄 null代表返回自身进程
        WinDef.HMODULE hmodule= Kernel32.INSTANCE.GetModuleHandle(null);
        //设置钩子 钩子类型,触发回调函数,所属进程,进程ID（0为全局钩子）
        hook=User32.INSTANCE.SetWindowsHookEx(WinUser.WH_KEYBOARD_LL,keyboardProc,hmodule,0);
        Thread.startVirtualThread(() -> {
            while(daConfig.color_picker){
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                    throw new RuntimeException(e);
                }
            }
        });
    }

    /**
     * 移除钩子
     */
    public void removeHook(){
        User32.INSTANCE.UnhookWindowsHookEx(hook);
    }
    /**
     * 监听到的按键
     * @param key
     */
    public void listenKey(String key) {
        Platform.runLater(() -> {
            hotkeys += (hotkeys.contains(key)?"":((hotkeys.isEmpty() ? "" : "+")+key));
            String[] qw = hotkeys.split("\\+");
            if (qw.length == 0) return;
            else if (qw.length == 1) {
                if (qw[0].equals("Shift") || qw[0].equals("Alt") || qw[0].equals("Windows") || qw[0].equals("Ctrl"))
                    return;
            } else if (qw.length == 2) {
                if (qw[1].equals("Shift") || qw[1].equals("Alt")) return;
            }
            boolean a=daConfig.color_picker_hot_key.replaceAll(" ","").equals(hotkeys);
            hotkeys = "";
            if (!a) return;
            Platform.runLater(()->{
                try {
                    new appColorPicker().start(new Stage());
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            });
        });
    }
    /**
     * 正确热键组合
     * 单个 > 非Ctrl、Windows、Alt、Shift、Fn、三
     * 两个 > Ctrl+? 或 Windows+? 或 Shift+?
     * 三个 > Ctrl+Alt+? 或 Ctrl+Shift+? 或 Windows+Shift+?
     * @param ks
     * @return
     */
    public boolean isHotkeyCorrect(String ks){
        String[] qw=ks.split("\\+");
        if(qw.length==0)return true;
        else if(qw.length==1){
            return !qw[0].equals("Alt");
        }else{
            if(qw[0].equals("Windows")){
                return !qw[1].equals("Alt");
            }
            if(qw.length==3){
                return !(qw[2].equals("Ctrl")||qw[2].equals("Windows")||qw[2].equals("Shift")||qw[2].equals("Alt"));
            }
        }
        return true;
    }

    /**
     * 检测热键是否完成
     * @param ks
     * @return
     */
    public boolean isHotkeyEnd(String ks){
        String[] qw=ks.split("\\+");
        if(qw.length==0)return false;
        else {
            int end=qw.length-1;
            return !(qw[end].equals("Ctrl") || qw[end].equals("Windows") || qw[end].equals("Shift") || qw[end].equals("Alt"));
        }
    }
}
